import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Row, Select, Cascader, Radio, Upload, Icon, message } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { getCatList, getSupplierType, addSupplier } from '@/services/supplier/addSupplier'
import ProvincesCascader from '@/components/ProvincesCascader'

const { Option } = Select

const AddSupplier = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [catList, setCatList] = useState([])  // 业态
  const [typeList, setTypeList] = useState([])  // 商户类型
  const [provinceId, setProvinceId] = useState('') // 省
  const [cityId, setCityId] = useState('') // 市
  const [areaId, setAreaId] = useState('') // 区
  const [loading, setLoading] = useState(false) // 图片加载

  useEffect(() => {
    init()
  }, [])

  const init = async () => {
    await getCatLists()
    await getSupplierTypes()
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Col span={8}>
        <Form.Item label={`名称`}>
          {getFieldDecorator(`id`, {})
            (<Input placeholder="请输入" />)}
        </Form.Item>
      </Col>
    )
  }
  // 按钮处理
  const handleBtn = type => {

  }
  // 返回按钮
  const goBack = () => {
    props.history.goBack(-1)
  }
  // 获取业态列表
  const getCatLists = async () => {
    let res = await getCatList()
    if (res.code === '0') {
      setCatList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 获取商户类型
  const getSupplierTypes = async () => {
    let res = await getSupplierType()
    if (res.code === '0') {
      setTypeList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 选择地址
  const selectAddress = (value, arr) => {
    setProvinceId(arr[0] ? arr[0].value : '')
    setCityId(arr[1] ? arr[1].value : '')
    setAreaId(arr[2] ? arr[2].value : '')
  }
  // 保存商户信息
  const saveSupplier = async () => {
    let params = {}
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      // console.log(provinceId, cityId, areaId)
      params = {
        status: '',
        userId: '',
        provinceId, // 省
        cityId, // 市
        areaId, // 区
        merchantName: values.merchantName,  // 商户名称
        carrieroperatorId: '1',
        logo: values.logo, // LOGO
        companyName: values.companyName, // 公司名称
        legalPerson: values.legalPerson, // 法人
        legalPhone: values.legalPhone, // 法人联系电话
        bank: values.bank, // 银行户名
        bankName: values.bankName, // 开户行名称
        bankAccount: values.bankAccount, // 开户行账号
        merchantsType: values.merchantsType, // 商户类型
        tradeId: values.tradeId, // 业态
        tradeName: '',
        platformAccess: values.platformAccess, // 允许平台接入
        businessLicence: values.businessLicence, // 营业执照
        images: [], // 商户图片
        address: values.address, // 楼栋楼层
        numberPlate: values.numberPlate, // 门牌号
        settleRate: values.settleRate, // 结算费率
        payRate: values.payRate, // 买单费率
        email: values.email // 注册账号(邮箱)
      }
    })
    let res = await addSupplier(params)
    if (res.code === '0') {
      alert(res.msg)
    } else {
      alert(res.msg)
    }
  }
  /* 图片处理 */
  function getBase64(img, callback) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Button type="primary" onClick={goBack}>返回</Button>
      <Form>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="商户名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('merchantName', {})
                (<Input placeholder="请输入运营商名称" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="业态" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('tradeId', {})
                (<Select
                  style={{ width: '100%' }}
                  showSearch
                  filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  placeholder="请选择"
                >
                  { catList && catList.map(r => <Option key={r.id} value={r.id}>{r.catName}</Option>)}
                </Select>)
              }
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="商户logo" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('logo', {})
                (<Input placeholder="请输入运营商名称" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="所在城市" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('city', {})
                (<ProvincesCascader onChange={selectAddress} />)}
            </Form.Item>
          </Col>

          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`楼栋楼层`}>
              {getFieldDecorator(`address`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`门牌号`}>
              {getFieldDecorator(`numberPlate`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`商户图片`}>
              {getFieldDecorator(`images`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`营业执照`}>
              {getFieldDecorator(`businessLicence`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`公司名称`}>
              {getFieldDecorator(`companyName`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`法人`}>
              {getFieldDecorator(`legalPerson`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`法人联系电话`}>
              {getFieldDecorator(`legalPhone`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`银行户名`}>
              {getFieldDecorator(`bank`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`开户行名称`}>
              {getFieldDecorator(`bankName`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`开户行账号`}>
              {getFieldDecorator(`bankAccount`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`商户类型`}>
              {getFieldDecorator(`merchantsType`, {})
                (<Select
                  style={{ width: '100%' }}
                  showSearch
                  filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  placeholder="请选择"
                >
                  { typeList && typeList.map(r => <Option key={r.value} value={r.value}>{r.label}</Option>)}
                </Select>)
              }
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`结算费率`}>
              {getFieldDecorator(`settleRate`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`公众平台接入`}>
              {getFieldDecorator(`platformAccess`, {
                initialValue: 1
              })
                (<Radio.Group>
                  <Radio value={1}>允许</Radio>
                  <Radio value={0}>不允许</Radio>
                </Radio.Group>)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`买单费率`}>
              {getFieldDecorator(`payRate`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} label={`注册账号(邮箱)`}>
              {getFieldDecorator(`email`, {})
                (<Input placeholder="请输入" />)}
            </Form.Item>
          </Col>
        </Row>
        <Button type="primary" style={{margin: '12px'}} onClick={e => saveSupplier()}>保存</Button>
        {/* <Button style={{margin: '12px'}}>取消</Button> */}
      </Form>
    </PageHeaderWrapper>
  )
}

export default Form.create()(AddSupplier)
